﻿using System;
using System.Data.OleDb;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Security.Cryptography;
using System.Text;

namespace BZZ{
/// <summary>
///bzzDataAcess 的摘要说明
/// </summary>
    /// 
    #region 数据操作类
    public class DataAcess
    {

        OleDbCommand _command = new OleDbCommand();
        public DataAcess()
        {
            _command.Parameters.Clear();
            /*_command.CommandType=CommandType.StoredProcedure;
            _command.Parameters.Add(new SqlParameter("@RETURN_VALUE",SqlDbType.Int ,4));
            _command.Parameters["@RETURN_VALUE"].Direction =ParameterDirection.ReturnValue;
            */
            _conString = (new ConfigData()).GetConnectString();
        }


        public DataSet Execute(string strSql)
        {
            OleDbConnection con = new OleDbConnection();
            DataSet dataSet = null;
            try
            {
                con.ConnectionString = _conString;
                //con.Open();
                _command.Connection = con;
                _command.CommandText = strSql;
                OleDbDataAdapter adapter = new OleDbDataAdapter(_command);
                dataSet = new DataSet();
                adapter.Fill(dataSet);
            }
            catch (System.Exception ex)
            {
                dataSet = null;
                throw ex;
            }
            finally
            {
                con.Close();
            }
            return dataSet;

        }

        //直接SQL语句并返回受影响的行数
        public int ExecuteNonQuery(string strSql)
        {
            OleDbConnection con = new OleDbConnection();
            int RowCount = -1;
            try
            {
                con.ConnectionString = _conString;
                con.Open();
                _command.CommandText = strSql;
                _command.Connection = con;
                RowCount = _command.ExecuteNonQuery();
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
            }
            return RowCount;
        }

        //返回结果集中的第一行第一列数据，忽略其他行或列
        public string ExecuteScalar(string strSql)
        {
            OleDbConnection con = new OleDbConnection();
            string RowValue = "None";
            try
            {
                con.ConnectionString = _conString;
                con.Open();
                _command.CommandText = strSql;
                _command.Connection = con;
                RowValue = _command.ExecuteScalar().ToString();
            }
            catch (System.Exception ex)
            {
                //throw ex;
            }
            finally
            {
                con.Close();
            }
            return RowValue;
        }

        //public DataSet Execute(SqlTransaction trans, string strSql)
        //{

        //    DataSet dataSet = null;
        //    try
        //    {
        //        _command.CommandText = strSql;
        //        _command.Connection = trans.Connection;
        //        _command.Transaction = trans;
        //        OleDbDataAdapter adapter = new OleDbDataAdapter(_command);
        //        dataSet = new DataSet();
        //        adapter.Fill(dataSet);


        //    }
        //    catch (System.Exception ex)
        //    {
        //        dataSet = null;
        //        throw ex;
        //    }

        //    return dataSet;

        //}
        //public int ExecuteNonQuery(SqlTransaction trans, string strSql)
        //{

        //    int RowCount = -1;
        //    try
        //    {
        //        _command.CommandText = strSql;
        //        _command.Connection = trans.Connection;
        //        _command.Transaction = trans;
        //        RowCount = _command.ExecuteNonQuery();

        //    }
        //    catch (System.Exception ex)
        //    {

        //        throw ex;
        //    }

        //    return RowCount;


        //}
        // 属性实现区域


        string _conString = "";
        public string ConnectStr
        {
            get { return _conString; }
            set { _conString = value; }
        }
        //只读属性
        //public SqlParameterCollection Parameters
        //{
        //    get { return _command.Parameters; }
        //}

    }
    #endregion

    #region commonFunctions
    public class CommonFunctions
    {
        public CommonFunctions() { ;}

        public bool IsLogin(System.Web.SessionState.HttpSessionState session,string level)
        {
            //if (session["admin"] == null || session["admin"] != "yes")
            //{
            //    return false;
            //}
            
            return true;
        }

        public bool isLogin(System.Web.HttpRequest requst)
        {

            if (requst.Cookies["admin"] == null) return false;
            else return true;
        }
        public bool IsValidateOperate(System.Web.SessionState.HttpSessionState session, string url, string cmd)
        {
            return true;
        }

        #region StringToMD5Hash
        public string StringToMD5Hash(string inputString)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] encryptedBytes = md5.ComputeHash(Encoding.ASCII.GetBytes(inputString));
            System.Text.StringBuilder sb = new StringBuilder();
            for (int i = 0; i < encryptedBytes.Length; i++)
            {
                sb.AppendFormat("{0:x2}", encryptedBytes[i]);
            }
            return sb.ToString();
        }
        #endregion

        #region  GetClientIP

        public string GetClientIP(System.Web.HttpRequest Request)
        {
            //return request.UserHostAddress;
            string user_IP = "";
            if (Request.ServerVariables["HTTP_VIA"] != null)
            {
                user_IP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else
            {
                user_IP = Request.ServerVariables["REMOTE_ADDR"].ToString();
            }
            return user_IP;
        }

        #endregion

        public string doneOK()
        {
            return doneOK("操作成功！");
        }
        public string doneOK(string message)
        {
            return doneOK(message, "?cmd=list");
        }
        public string doneOK(string message, string gotoUrl)
        {
            return doneOK(message, gotoUrl, 0);
        }
        public string doneOK(string message, string gotoUrl, int method)
        {
            string rtn = "";
            switch (method)
            {
                case 0:
                    rtn = "<script>alert('" + message + "');this.location.href='" + gotoUrl + "';</script>";
                    break;
                case 1:
                    rtn = "<font color=red>" + message + "</font>,<a href='" + gotoUrl + "'>3秒后自动跳转</a>.";
                    break;
                case 2:
                    rtn = "<script>alert('" + message + "');this.location.href='" + gotoUrl + "';</script>";
                    break;
            }
            return rtn;
        }

        public string doneFailed()
        {
            return doneFailed("操作失败！", "", 2);
        }
        public string doneFailed(string message)
        {
            return doneFailed(message, "", 2);
        }
        public string doneFailed(string message, string gotoUrl, int method)
        {
            string rtn = "";
            switch (method)
            {
                case 0:
                    rtn = "<script>alert('" + message + "');this.location.href='" + gotoUrl + "';</script>";
                    break;
                case 1:
                    rtn = "错误提示：<font color=red>" + message + "</font>,点<a href='javascript:history.go(-1);'>此处后退</a>到上一页。";
                    break;
                case 2:
                    rtn = "<script>alert('" + message + "');history.go(-1);</script>";
                    break;
                case 3:
                    rtn = "<script>alert('" + message + "');this.location.href='" + gotoUrl + "';</script>";
                    break;
            }
            return rtn;
        }
        public string doneFailed(string message, string gotoUrl)
        {
            return doneFailed(message, gotoUrl, 0);
        }

        #region get page html
        /// <summary>
        /// 获取翻页的链接
        /// </summary>
        /// <param name="CurrentPageNum">当前页码</param>
        /// <param name="RecordCount">记录总条数</param>
        /// <param name="PageSize">每页记录数</param>
        /// <param name="paraStr">跳转传送参数</param>
        /// <returns>html页面</returns>
        public string getPageHtml(int CurrentPageNum, int RecordCount, int PageSize, string paraStr)
        {
            string ret = "<div class=\"divPage\">";
            int pageNum = (RecordCount - 1) / PageSize + 1;
            bool isFirstPage = false;
            bool isLastPage = false;
            if (CurrentPageNum <= 1) isFirstPage = true;
            if (CurrentPageNum >= pageNum) isLastPage = true;

            ret += "共 " + pageNum.ToString() + " 页 ";
            ret += " " + RecordCount.ToString() + " 条记录 ";
            if (isFirstPage) ret += " 首页 上一页 ";
            else ret += "<a href=\"?p=1&" + paraStr + "\" class=\"navPage\" >首页</a> <a href=\"?p=" + Convert.ToString(CurrentPageNum - 1) + "&" + paraStr + "\" class=\"navPage\">上一页</a>";
            if (isLastPage) ret += " 下一页 尾页 ";
            else ret += " <a href=\"?p=" + Convert.ToString(CurrentPageNum + 1) + "&" + paraStr + "\" class=\"navPage\">下一页</a> <a href=\"?p=" + pageNum.ToString() + "&" + paraStr + "\" class=\"navPage\" >尾页</a>";

            //ret += "当前是第" + CurrentPageNum.ToString() + " 页 ";
            ret += " 转到：<select  name=p size=1 onchange=\"window.location='?p='+this.options[this.selectedIndex].value+'&" + paraStr + "';\"> ";
            for (int i = 1; i <= pageNum; i++)
            {
                ret += "<option value='" + i.ToString() + "' ";
                if (i == CurrentPageNum)
                    ret += " selected ";
                ret += ">第" + i.ToString() + "页</option>";
            }
            ret += "</select>";
            ret += "</div>";
            return ret;
        }

        public string getPageHtml(int RecordCount, int PageSize, string paraStr, System.Web.HttpRequest Request)
        {
            if (paraStr != "") paraStr = "&" + paraStr;
            string ret = "<div class=\"divPage\">";
            int pageNum = (RecordCount - 1) / PageSize + 1;
            bool isFirstPage = false;
            bool isLastPage = false;
            int CurrentPageNum = 1;
            try
            {
                CurrentPageNum = Convert.ToInt32(Request["page"]);
            }
            catch { }
            if (CurrentPageNum <= 1) isFirstPage = true;
            if (CurrentPageNum >= pageNum) isLastPage = true;

            ret += "共 " + pageNum.ToString() + " 页 ";
            ret += " " + RecordCount.ToString() + " 条记录 ";
            if (isFirstPage) ret += " 首页 上一页 ";
            else ret += "<a href=\"?page=1" + paraStr + "\" class=\"navPage\" >首页</a> <a href=\"?page=" + Convert.ToString(CurrentPageNum - 1) + "" + paraStr + "\" class=\"navPage\">上一页</a>";
            if (isLastPage) ret += " 下一页 尾页 ";
            else ret += " <a href=\"?page=" + Convert.ToString(CurrentPageNum + 1) + "" + paraStr + "\" class=\"navPage\">下一页</a> <a href=\"?page=" + pageNum.ToString() + "" + paraStr + "\" class=\"navPage\" >尾页</a>";

            //ret += "当前是第" + CurrentPageNum.ToString() + " 页 ";
            ret += " 转到：<select  name=p size=1 onchange=\"window.location='?page='+this.options[this.selectedIndex].value+'" + paraStr + "';\"> ";
            for (int i = 1; i <= pageNum; i++)
            {
                ret += "<option value='" + i.ToString() + "' ";
                if (i == CurrentPageNum)
                    ret += " selected ";
                ret += ">第" + i.ToString() + "页</option>";
            }
            ret += "</select>";
            ret += "</div>";
            return ret;
        }
        #endregion
    }
    
    #endregion

    #region  获取web.config数据
    public class ConfigData
    {

        //fields
        private System.Configuration.Configuration _configHelp = null;
        private static string _strDefaultCon = "myDefaultConstring";

        //methods
        public ConfigData(string strConfigVirtualPath)
        {
            _configHelp = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(strConfigVirtualPath);

        }
        public ConfigData()
        {
            _configHelp = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(HttpRuntime.AppDomainAppVirtualPath);

        }
        public string GetConnectString(string strKey)
        {
            return _configHelp.ConnectionStrings.ConnectionStrings[strKey].ConnectionString;
        }

        public string GetConnectString()
        {
            return _configHelp.ConnectionStrings.ConnectionStrings[_strDefaultCon].ConnectionString;
        }
        public string GetAppSeting(string strKey)
        {
            return _configHelp.AppSettings.Settings[strKey].Value;
        }

        public static string GetConnectstring()
        {
            return System.Web.Configuration.WebConfigurationManager.ConnectionStrings[_strDefaultCon].ConnectionString;

        }
        public static string GetConnectstring(string strKey)
        {
            return System.Web.Configuration.WebConfigurationManager.ConnectionStrings[strKey].ConnectionString;

        }

        #region StringToMD5Hash
        public string StringToMD5Hash(string inputString)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] encryptedBytes = md5.ComputeHash(Encoding.ASCII.GetBytes(inputString));
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            for (int i = 0; i < encryptedBytes.Length; i++)
            {
                sb.AppendFormat("{0:x2}", encryptedBytes[i]);
            }
            return sb.ToString();
        }
        #endregion


        #region  GetClientIP

        public string GetClientIP(System.Web.HttpRequest Request)
        {
            //return request.UserHostAddress;
            string user_IP = "";
            if (Request.ServerVariables["HTTP_VIA"] != null)
            {
                user_IP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else
            {
                user_IP = Request.ServerVariables["REMOTE_ADDR"].ToString();
            }
            return user_IP;
        }

        #endregion


    }
    #endregion
}
